package com.erik.lin.inteceptor;

import com.erik.lin.annotion.MenuVerify;
import com.erik.lin.annotion.PermissionIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by Erik on 2017/8/21.
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    Logger LOG = LoggerFactory.getLogger(PermissionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            LOG.info("不需要校验权限，不是handlerMethod");
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(PermissionIgnore.class)) {
            LOG.info("忽略校验权限IgnorePermission，handlerMethod-{}", method);
            return true;
        }

        if (!method.isAnnotationPresent(MenuVerify.class) || !(handlerMethod.getBeanType().isAnnotationPresent(MenuVerify.class))) {
            LOG.info("未配置权限校验MenuVerify，handlerMethod-{}", method);
            return true;
        }

        LOG.info("经过权限校验");

        return true;
    }
}

